package cn.bugstack.mybatis.builder.xml;

import cn.bugstack.mybatis.builder.BaseBuilder;
import cn.bugstack.mybatis.builder.MapperBuilderAssistant;
import cn.bugstack.mybatis.mapping.MappedStatement;
import cn.bugstack.mybatis.mapping.SqlCommandType;
import cn.bugstack.mybatis.mapping.SqlSource;
import cn.bugstack.mybatis.scripting.LanguageDriver;
import cn.bugstack.mybatis.session.Configuration;

import org.dom4j.Element;

import java.util.Locale;

/**
 *    <select id="selectBlog" parameterType="int" resultType="Blog">
 *      select * from Blog where id = #{id}
 *    </select>
 */
public class XmlStatementBuilder extends BaseBuilder {
    private Element element;

    private MapperBuilderAssistant builderAssistant;

    public XmlStatementBuilder(Configuration configuration, Element element, MapperBuilderAssistant builderAssistant) {
        super(configuration);
        this.element = element;
        this.builderAssistant = builderAssistant;
    }

    /**
     *   <select id="selectBlog" parameterType="int" resultType="Blog">
     *     select * from Blog where id = #{id}
     *   </select>
     *
     * @throws Exception
     */
    public void parseStatementNode() throws Exception{
        String id = element.attributeValue("id");
        String parameterType = element.attributeValue("parameterType");
        Class<?> parameterTypeClass = resolveAlias(parameterType);

        String resultType = element.attributeValue("resultType");
        Class<?> resultTypeClass = resolveAlias(resultType);

        // 外部应用 resultMap
        String resultMap = element.attributeValue("resultMap");

        // select语句唯一标识


        // 获取sql的类型 insert | select | update | delete
        String nodeName = element.getName();
        SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));

        // 获取默认的语言驱动器
        LanguageDriver defaultDriver = configuration.getLanguageRegistry().getDefaultDriver();

        SqlSource sqlSource = defaultDriver.createSqlSource(configuration, element, parameterTypeClass);



        builderAssistant.addMappedStatement(id,sqlSource, sqlCommandType , parameterTypeClass,resultMap, resultTypeClass,defaultDriver);





    }


}
